from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource,marshal,reqparse
import json
from common.utils.login_utils import login_required
from models import db
from models.user import Collection
channel = Blueprint('channel',__name__,url_prefix='/channle')
api = Api(channel)
from models.user import Channel,News,UserModel
from common.model_fields.user import channels_fields
class ChannlesResource(Resource):
    def get(self):
        """获取所有的频道信息"""
        channels = Channel.query.all()
        return marshal(channels,channels_fields)
from common.model_fields.user import news_fields
class NewByChannel(Resource):
    def get(self):
        """根据文章id，获取文章信息"""
        parser = reqparse.RequestParser()
        parser.add_argument('category')
        args = parser.parse_args()
        cate_id = args.get('category')
        news = News.query.filter_by(channel_id = cate_id).all()
        # 把有序字典转换字典，然后给每篇文章添加作者信息
        datas = json.loads(json.dumps(marshal(news,news_fields)))

        for new in datas:
            user = UserModel.query.filter_by(uid=new['user_id']).first()
            new['nick_name'] = user.uname
        print("data", datas)
        return jsonify(message='ok',code=200,data={'news':datas})

class NewInfo(Resource):
    def get(self,id):
        new = News.query.filter_by(nid=id).first()
        data = json.loads(json.dumps(marshal(new,news_fields)))
        user = UserModel.query.filter_by(uid=new.user_id).first()
        data['nick_name']  = user.uname
        return jsonify(message='ok',code=200,data=data)

class CollectionResource(Resource):

    @login_required
    def get(self,nid):
        """
        添加文章收藏
        1. 实现这个功能前提是必须先登录
        2. 只有登录后的才能实现点赞
        3. 从收藏表去查询,文章是否被收藏: 根据user_id, news_id 去查询,返回的是一个文章信息
        :param id:  文章的id
        :return:
        """
        # 获取当前登录的用户id
        uid = g.user_id
        rest = Collection.query.filter_by(user_id=uid, news_id=nid).first()
        # 若过滤出信息, 修改文章的is_collection的值
        if not rest:
            # 创建收藏表
            collect = Collection(user_id=uid, news_id=nid)
            db.session.add(collect)
            db.session.commit()
            # 5555555
            # 修ush改的是收藏的状态
            News.query.filter_by(nid=nid).update({'is_collection':1})
            db.session.commit()
            return jsonify(message='收藏成功', code=200)
        else:
            # 取消收藏时要把收藏表中的数据删除, 但是不会物理删除, 只是逻辑删除
            Collection.query.filter_by(user_id=uid, news_id=nid).update({'is_delete':1})
            db.session.commit()
            # 没有结果说明取消收藏
            News.query.filter_by(nid=nid).update({'is_collection': 0})
            db.session.commit()
            return jsonify(message='取消收藏成功', code=200)

api.add_resource(ChannlesResource,'/channle')
api.add_resource(NewByChannel,'/news/channel')
api.add_resource(NewInfo,'/info/<int:id>')
api.add_resource(CollectionResource,'/starts/<int:nid>')